<template>
  <div class="user-list-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddUser" v-if="checkPermission('sys:user:add')">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" v-if="checkPermission('sys:user:delete')" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" layout="inline" size="small" @submit.prevent>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="180" />
        <el-table-column prop="name" label="用户名" width="180">
          <template #default="scope">
            <el-popover
              trigger="hover"
              placement="top"
            >
              <div class="user-info-popover">
                <div class="user-avatar">
                  <el-avatar :size="48">
                    {{ scope.row.name.charAt(0).toUpperCase() }}
                  </el-avatar>
                </div>
                <div class="user-details">
                  <p class="user-name">{{ scope.row.name }}</p>
                  <p class="user-email">{{ scope.row.email }}</p>
                  <p class="user-status">{{ scope.row.status === 1 ? '启用' : '禁用' }}</p>
                </div>
              </div>
              <template #reference>
                <span>{{ scope.row.name }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="240" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
              v-if="checkPermission('sys:user:edit')"
            />
            <span v-else>{{ scope.row.status === 1 ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditUser(scope.row)"
              v-if="checkPermission('sys:user:edit')"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(scope.row.id)"
              v-if="checkPermission('sys:user:delete')"
              :disabled="scope.row.id === currentUserId"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleAssignRoles(scope.row)"
              v-if="checkPermission('sys:user:assignRole')"
            >
              <el-icon><Avatar /></el-icon>
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item prop="name">
          <el-input
            v-model="userForm.name"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="userForm.email"
            type="email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        <el-form-item prop="password" v-if="!userForm.id">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item prop="status">
          <el-switch
            v-model="userForm.status"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <el-form :model="assignRoleForm">
        <el-form-item label="当前用户">
          <el-input v-model="assignRoleForm.username" disabled />
        </el-form-item>
        <el-form-item label="已分配角色">
          <el-select
            v-model="assignRoleForm.roleIds"
            multiple
            collapse-tags
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRoles">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'UserList',
  setup() {
    // 表格数据和加载状态
    const userList = ref([])
    const loading = ref(false)
    const selectedRows = ref([])
    const currentUserId = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      username: '',
      email: '',
      status: ''
    })
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const dialogTitle = ref('')
    
    // 用户表单
    const userFormRef = ref(null)
    const userForm = reactive({
      id: '',
      name: '',
      email: '',
      password: '',
      status: 1
    })
    
    // 用户表单验证规则
    const userRules = {
      name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }
    
    // 角色数据
    const roleList = ref([])
    const assignRoleForm = reactive({
      userId: '',
      username: '',
      roleIds: []
    })
    
    // 加载用户列表
    const loadUserList = async () => {
      try {
        loading.value = true
        
        // 这里应该调用后端API获取真实数据
        // 由于是模拟环境，我们使用mock数据
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // Mock用户数据
        const mockData = [
          {
            id: 1,
            name: '张三',
            email: 'zhangsan@example.com',
            status: 1,
            createTime: '2025-09-01 10:20:30',
            updateTime: '2025-09-10 15:30:45'
          },
          {
            id: 2,
            name: '李四',
            email: 'lisi@example.com',
            status: 1,
            createTime: '2025-09-02 09:15:20',
            updateTime: '2025-09-05 14:25:10'
          },
          {
            id: 3,
            name: '王五',
            email: 'wangwu@example.com',
            status: 0,
            createTime: '2025-09-03 11:30:45',
            updateTime: '2025-09-08 16:40:25'
          },
          {
            id: 4,
            name: '赵六',
            email: 'zhaoliu@example.com',
            status: 1,
            createTime: '2025-09-04 13:25:15',
            updateTime: '2025-09-09 10:15:30'
          },
          {
            id: 5,
            name: '钱七',
            email: 'qianqi@example.com',
            status: 1,
            createTime: '2025-09-05 15:40:30',
            updateTime: '2025-09-10 09:25:45'
          }
        ]
        
        // 模拟分页
        const startIndex = (pagination.currentPage - 1) * pagination.pageSize
        const endIndex = startIndex + pagination.pageSize
        userList.value = mockData.slice(startIndex, endIndex)
        pagination.total = mockData.length
        
        // 设置当前用户ID（用于禁止删除自己）
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        currentUserId.value = userInfo.id || 1
        
      } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载用户列表失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 加载角色列表
    const loadRoleList = async () => {
      try {
        // Mock角色数据
        roleList.value = [
          { id: 1, name: '系统管理员', code: 'ADMIN' },
          { id: 2, name: '普通用户', code: 'USER' },
          { id: 3, name: '只读用户', code: 'READONLY' }
        ]
      } catch (error) {
        console.error('加载角色列表失败:', error)
        ElMessage.error('加载角色列表失败')
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      loadUserList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.currentPage = 1
      loadUserList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadUserList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      loadUserList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (rows) => {
      selectedRows.value = rows
    }
    
    // 处理状态变化
    const handleStatusChange = async (row) => {
      try {
        // 这里应该调用后端API更新用户状态
        ElMessage.success('状态更新成功')
      } catch (error) {
        console.error('更新状态失败:', error)
        // 失败时回滚状态
        row.status = row.status === 1 ? 0 : 1
        ElMessage.error('更新状态失败，请稍后重试')
      }
    }
    
    // 处理新增用户
    const handleAddUser = () => {
      dialogTitle.value = '新增用户'
      // 重置表单
      Object.keys(userForm).forEach(key => {
        userForm[key] = ''
      })
      userForm.status = 1
      dialogVisible.value = true
    }
    
    // 处理编辑用户
    const handleEditUser = (row) => {
      dialogTitle.value = '编辑用户'
      // 复制用户数据到表单
      Object.assign(userForm, { ...row })
      // 编辑时清空密码
      userForm.password = ''
      dialogVisible.value = true
    }
    
    // 处理保存用户
    const handleSaveUser = async () => {
      try {
        await userFormRef.value.validate()
        
        // 这里应该调用后端API保存用户
        
        if (userForm.id) {
          // 编辑用户
          ElMessage.success('用户编辑成功')
        } else {
          // 新增用户
          ElMessage.success('用户新增成功')
        }
        
        // 关闭对话框并刷新列表
        dialogVisible.value = false
        loadUserList()
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('保存用户失败，请稍后重试')
      }
    }
    
    // 处理删除用户
    const handleDeleteUser = async (id) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除该用户吗？此操作不可撤销。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用后端API删除用户
        
        ElMessage.success('用户删除成功')
        loadUserList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error('删除用户失败，请稍后重试')
        }
      }
    }
    
    // 处理批量删除
    const handleBatchDelete = async () => {
      try {
        if (selectedRows.value.length === 0) {
          ElMessage.warning('请先选择要删除的用户')
          return
        }
        
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedRows.value.length} 个用户吗？此操作不可撤销。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用后端API批量删除用户
        
        ElMessage.success('用户批量删除成功')
        selectedRows.value = []
        loadUserList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除用户失败:', error)
          ElMessage.error('批量删除用户失败，请稍后重试')
        }
      }
    }
    
    // 处理分配角色
    const handleAssignRoles = (row) => {
      assignRoleForm.userId = row.id
      assignRoleForm.username = row.name
      // 这里应该调用后端API获取用户已分配的角色
      // 模拟数据
      assignRoleForm.roleIds = row.id % 2 === 0 ? [1] : [2]
      roleDialogVisible.value = true
    }
    
    // 处理保存角色分配
    const handleSaveRoles = async () => {
      try {
        // 这里应该调用后端API保存角色分配
        
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
      } catch (error) {
        console.error('保存角色分配失败:', error)
        ElMessage.error('保存角色分配失败，请稍后重试')
      }
    }
    
    // 处理对话框关闭
    const handleDialogClose = () => {
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }
    
    // 检查权限
    const checkPermission = (permissionCode) => {
      // 从localStorage获取用户权限
      const permissions = JSON.parse(localStorage.getItem('permissions') || '[]')
      // 检查是否包含所需权限
      return permissions.includes(permissionCode)
    }
    
    onMounted(() => {
      loadUserList()
      loadRoleList()
    })
    
    return {
      userList,
      loading,
      selectedRows,
      currentUserId,
      searchForm,
      pagination,
      dialogVisible,
      roleDialogVisible,
      dialogTitle,
      userFormRef,
      userForm,
      userRules,
      roleList,
      assignRoleForm,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleStatusChange,
      handleAddUser,
      handleEditUser,
      handleSaveUser,
      handleDeleteUser,
      handleBatchDelete,
      handleAssignRoles,
      handleSaveRoles,
      handleDialogClose,
      checkPermission
    }
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-form {
  max-height: 400px;
  overflow-y: auto;
}

/* 用户信息弹窗样式 */
.user-info-popover {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.user-email {
  color: #909399;
  font-size: 12px;
  margin-bottom: 4px;
}

.user-status {
  color: #67c23a;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .el-form--inline .el-form-item {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .el-form--inline .el-input {
    width: 100% !important;
  }
}
</style>